//
//  HMCartController.m
//  HMMarket
//
//  Created by 孙鹏飞 on 2017/5/9.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "HMCartController.h"
#import "HMCustomCartTableViewCell.h"
#import "HMEditCartTableViewCell.h"
#import "HttpBaseTool.h"
#import "CartModel.h"
#import "HMSubmitOrderViewController.h"
#import "HMNoDataReload.h"

@interface HMCartController ()<UITableViewDelegate, UITableViewDataSource, HMEditCartTableViewCellDelegate>

NS_STRONG UITableView *myTableView;

NS_ASSIGN BOOL edite;

NS_ASSIGN BOOL selectAll;

NS_STRONG NSMutableArray *dataArray;

NS_COPY NSString *user_tel;

NS_ASSIGN float countTotalPrice;

@property (weak, nonatomic) IBOutlet UIButton *submitOrderBtn;

@property (weak, nonatomic) IBOutlet UILabel *totalPrice;
@property (weak, nonatomic) IBOutlet UIButton *selectAllBtn;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
NS_STRONG UIImageView * nodata;
@property (weak, nonatomic) IBOutlet UIView *backView;
NS_STRONG HMNoDataReload *reload;
NS_STRONG UIButton *pushToHomeBtn;
@end

@implementation HMCartController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"购物车";
    [self setUpSubView];
}

- (void)setUpSubView {
    _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 48 - 64) style:UITableViewStyleGrouped];
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    [_myTableView setSeparatorColor:[UIColor colorWithRed:235/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1]];
    [self.view addSubview:_myTableView];
    
    _nodata =[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"default_shoppingcart"]];
    _nodata.width = 124;
    _nodata.height = 145;
    _nodata.centerX =KWidthSCREEN/2;
    _nodata.centerY =(KHeightSCREEN - 250)/2;
    [self.myTableView addSubview:_nodata];
    
    _pushToHomeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _pushToHomeBtn.frame = CGRectMake(_nodata.frame.origin.x, CGRectGetMaxY(_nodata.frame) + 18, _nodata.frame.size.width, 40);
    [_pushToHomeBtn setBackgroundColor:kMainColor];
    [_pushToHomeBtn setTitle:@"去逛逛" forState:UIControlStateNormal];
    _pushToHomeBtn.layer.cornerRadius = 5;
    _pushToHomeBtn.clipsToBounds = YES;
    [_pushToHomeBtn addTarget:self action:@selector(popToRootVC) forControlEvents:UIControlEventTouchUpInside];
    [self.myTableView addSubview:_pushToHomeBtn];

    
    [self.RightBarItem setTitle:@"编辑" forState:UIControlStateNormal];
    [self.RightBarItem setTitle:@"完成" forState:UIControlStateSelected];
    self.RightBarItem.selected = _edite;
    [self.RightBarItem addTarget:self action:@selector(changeCartStatus) forControlEvents:UIControlEventTouchUpInside];
    
    [_selectAllBtn addTarget:self action:@selector(selectAllOrder) forControlEvents:UIControlEventTouchUpInside];
    [_selectAllBtn setImage:[UIImage imageNamed:@"Cart_disSelect"] forState:UIControlStateNormal];
    [_selectAllBtn setImage:[UIImage imageNamed:@"Cart_select"] forState:UIControlStateSelected];
    
    [_submitOrderBtn setBackgroundColor:kMainColor];
    [_submitOrderBtn addTarget:self action:@selector(pushToSubmitOrderVC) forControlEvents:UIControlEventTouchUpInside];
    
    [_deleteBtn addTarget:self action:@selector(deleteCartOrder) forControlEvents:UIControlEventTouchUpInside];
    [_deleteBtn setBackgroundColor:kMainColor];
    _deleteBtn.hidden = YES;
    
    _totalPrice.textColor = kPriceTextColor;
    
    [self setExtraCellLineHidden:_myTableView];
    [self getData];
}

- (void)popToRootVC {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)pushToSubmitOrderVC {
    NSMutableArray *submitArray = [NSMutableArray array];
    for (int i = 0; i < _dataArray.count; i++) {
        CartModel *model = _dataArray[i];
        if (model.select == YES) {
            [submitArray addObject:model];
        }
    }
    if (submitArray.count == 0) {
        [HMHUDManager showHUDWithText:@"请选择需要购买的商品"];
    } else {
        HMSubmitOrderViewController *vc = [[HMSubmitOrderViewController alloc] init];
        vc.dataArray = submitArray;
        vc.refresh = ^void *(NSString *noting) {
            [self getData];
            return nil;
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)changeCartStatus {
    _edite = !_edite;
    self.RightBarItem.selected = _edite;
    if (_edite) {
        _totalPrice.hidden = YES;
        _deleteBtn.hidden = NO;
    } else {
        _totalPrice.hidden = NO;
        _deleteBtn.hidden = YES;
        [self countAndGetTotalPrice];
    }
}

- (void)selectAllOrder{
    _selectAllBtn.selected = !_selectAllBtn.selected;
    for (int i = 0; i < _dataArray.count; i++) {
       CartModel *model = _dataArray[i];
        model.select = _selectAllBtn.selected;
    }
    [_myTableView reloadData];
    
    [self countAndGetTotalPrice];
}

//删除订单
- (void)deleteCartOrder {
    NSMutableArray *deleteCartArray = [NSMutableArray array];
    NSMutableArray *totalId = [NSMutableArray array];
    for (int i = 0; i < _dataArray.count; i++) {
        CartModel *model = _dataArray[i];
        if (model.select == YES) {
            [deleteCartArray addObject:model];
            [totalId addObject:model.cid];
        }
    }
    [HttpBaseTool post:kCartDelete params:@{@"user_tel":[MGAccountTool getTel], @"cid":totalId} success:^(id responseObj) {
        if ([responseObj[@"code"] integerValue] == 200) {
            [HMHUDManager showHUDWithText:@"删除成功"];
            [_dataArray removeObjectsInArray:deleteCartArray];
            [self.myTableView reloadData];
            LoginSuccess;
            if (_dataArray.count == 0) {
                _nodata.hidden = NO;
                _pushToHomeBtn.hidden = NO;
                
                _backView.hidden = YES;
                self.RightBarItem.hidden = YES;
                _myTableView.frame = CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 64);
            }
        } else {
            [HMHUDManager showHUDWithText:@"msg"];
        }
    } failure:^(NSError *error) {
        
    }];
    
}
//获取购物车信息
- (void)getData {
    DefaultWeakSelf;
    [HttpBaseTool get:kCartInfo params:@{@"user_tel":[MGAccountTool getTel]} success:^(id responseObj) {
        if (_reload !=nil) {
            [_reload removeFromSuperview];
        }
        _dataArray = [CartModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
        if (self.dataArray.count == 0) {
            _nodata.hidden = NO;
            _pushToHomeBtn.hidden = NO;
//            _submitOrderBtn.hidden = YES;
//            _totalPrice.hidden = YES;
//            _selectAllBtn.hidden = YES;
//            _deleteBtn.hidden = YES;
            _backView.hidden = YES;
            self.RightBarItem.hidden = YES;
            _myTableView.frame = CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 64);
        } else {
            _nodata.hidden = YES;
            _pushToHomeBtn.hidden = YES;
            _backView.hidden = NO;
            self.RightBarItem.hidden = NO;
            _myTableView.frame = CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 64 - 48);
        }
        [_myTableView reloadData];
    } failure:^(NSError *error) {
        _nodata.hidden = YES;
        _pushToHomeBtn.hidden = YES;
        _backView.hidden = YES;
        _myTableView.frame = CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 64);
        weakSelf.reload.reloadData = ^void *{
            [weakSelf getData];
            return nil;
        };
        [self.view addSubview:self.reload];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HMEditCartTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"HMEditCartTableViewCell" owner:self options:nil] firstObject];
    cell.index = indexPath;
    cell.dataArray = _dataArray;
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 95;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001;
}

-(void)viewDidLayoutSubviews
{
    if ([self.myTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.myTableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.myTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.myTableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - HMEditCartTableViewCellDelegate
- (void)changeNumber:(changeNumber)state {
    [self countAndGetTotalPrice];
}

- (void)changeStatus:(BOOL)select {
    if (select == NO) {
        _selectAllBtn.selected = NO;
    }
    [self countAndGetTotalPrice];
}

//计算价钱
- (void)countAndGetTotalPrice{
    _countTotalPrice = 0.f;
    for (int i = 0; i < _dataArray.count; i++) {
        CartModel *model = _dataArray[i];
        if (model.select == YES) {
            _countTotalPrice = _countTotalPrice + [model.item_price floatValue] * [model.item_number integerValue];
            MyLog(@"%.2f", _countTotalPrice);
        }
    }
    _totalPrice.text = [NSString stringWithFormat:@"合计：¥%.2f", _countTotalPrice];
}

-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}

- (HMNoDataReload *)reload {
    if (_reload == nil) {
        _reload = [[HMNoDataReload alloc] init];
    }
    return _reload;
}

@end
